package com.example.demo.serviceImpl;

import com.example.demo.dao.OrderDao;
import com.example.demo.entity.Order;
import com.example.demo.entity.ResultMsg;
import com.example.demo.feignClient.StoreClient;
import com.example.demo.feignClient.UserClient;
import com.example.demo.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author user
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;
    @Resource
    private UserClient userClient;
    @Resource
    private StoreClient storeClient;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResultMsg insertOrder(Byte companyId, Long userId, Long productId, int amount) {
        System.out.println("事务id:" + RootContext.getXID());
        //新增订单
        Order order = new Order();
        order.setUserId(userId);
        order.setCreatedAt(new Date());
        order.setProductId(productId);
        order.setCompanyId(companyId);
        orderDao.insert(order);
        //调用用户服务，更新用户的下单数量
//        userClient.updateUserOrderAmount(userId, amount, companyId);
        //调用库存服务，扣减商品库存
        storeClient.updateStore(productId, amount);
        int i = 1 / 0;
        return ResultMsg.ok();
    }

    @Override
    public ResultMsg detail(Long orderId) {
        return ResultMsg.successfulData(orderDao.selectByPrimaryKey(orderId));
    }
}
